import SwiftUI

struct SearchView: View {
    @State private var searchText: String = ""
    @State private var searchHistory: [String] = ["Nikke", "Cosplay", "WEBTOON"]
    @Environment(\.dismiss) var dismiss
    @StateObject private var viewModel = MainPicaViewModel()
    @State private var hasAppeared = false
    @FocusState private var isSearchFieldFocused: Bool  // FocusState
    
    var body: some View {
        VStack {
            // 搜索行
            HStack {
                Button {
                    isSearchFieldFocused = false
                    dismiss()
                } label: {
                    Image(systemName: "chevron.left")
                        .font(.system(size: 20))
                        .foregroundStyle(.white)
                }
                .padding(10)
                
                Spacer()
                
                TextField("请输入关键词...", text: $searchText)
                    .focused($isSearchFieldFocused)  // 绑定 FocusState
                    .padding(8)
                    .background(Color("BgColor2"))
                    .cornerRadius(10)
                    .frame(height: 40)
                    .foregroundColor(.white)
                
                Spacer()
                
                Button(action: {
                    // Perform search action
                    isSearchFieldFocused = false
                    if !searchText.isEmpty {
                        // 如果 searchHistory 中不包含当前的 searchText，就插入
                        if !searchHistory.contains(searchText) {
                            searchHistory.insert(searchText, at: 0)
                        }
                        viewModel.get_search_data(name: searchText)
                    }
                    
                }) {
                    Text("搜索")
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                }
                .padding(10)
            }
            
            // 搜索历史
            VStack(alignment: .leading) {
                HStack{
                    Text("搜索历史")
                        .foregroundColor(.white)
                    Spacer()
                }
                
                // 使用 LazyVGrid 的 .adaptive 来实现自动换行
                HStack{
                    ForEach(searchHistory.filter { !$0.isEmpty }, id: \.self) { historyItem in
                        Text(historyItem)
                            .font(.system(size: 14))
                            .foregroundStyle(.white)
                            .padding(6)
                            .background(Color.white.opacity(0.2))  // 背景色
                            .clipShape(RoundedRectangle(cornerRadius: 6))  // 圆角
                            .overlay(
                                RoundedRectangle(cornerRadius: 6)  // 边框的圆角
                                    .stroke(Color.gray, lineWidth: 1)  // 灰色边框
                            )
                            .fixedSize(horizontal: true, vertical: false)
                            .onTapGesture {
                                // 选择历史项时的动作
                                searchText = historyItem
                                viewModel.get_search_data(name: historyItem)
                            }
                    }
                }
                
                
                .padding(.top,10)
            }
            .padding(.top)
            .padding(.horizontal,10)
            
            HStack{
                Text("猜你想搜")
                    .foregroundColor(.white)
                Spacer()
                Button(action: {
                    viewModel.get_tj_data()
                }) {
                    Image(systemName: "arrow.clockwise")
                        .font(.system(size: 20))
                        .foregroundStyle(.white)
                }
            }
            .padding(.top)
            .padding(.horizontal,10)
            
            ScrollView(.horizontal) {
                LazyHStack(spacing: 20) {
                    ForEach(viewModel.search_tuijian, id: \.id) { item in
                        NavigationLink {
                            DetailView(item: item)
                        } label: {
                            DiscoverTopCard(item: item,tag:"hot")
                                .frame(width: 120,height:150)
                        }
                    }
                }
            }.frame(height:150)
            .scrollIndicators(.hidden) // 隐藏滚动条
            .padding(.horizontal,10)
            .padding(.bottom,20)
            
            VStack{

                Text("搜索结果")
                    .foregroundColor(.white)
                    .padding(.horizontal,10)
                    .padding(.top,15)
                    .frame(maxWidth: .infinity, alignment: .leading)
                ScrollView {
                    if viewModel.search_dats.isEmpty {
                        // 没有搜索结果时，显示空箱子图标和提示文本
                        VStack {
                            Spacer()
                            Image(systemName: "tray")
                                .font(.system(size: 60))
                                .foregroundColor(.gray)
                                .padding(.top,30)
                            Text("暂无搜索结果")
                                .foregroundColor(.gray)
                                .font(.system(size: 14))
                                .padding(.top,20)
                            Spacer()
                        }
                        .frame(maxWidth: .infinity)
                        .padding(.top, 50)
                    } else {
                        // 有搜索结果时，显示搜索内容
                        LazyVStack(spacing: 10) {
                            ForEach(viewModel.search_dats, id: \.id) { item in
                                NavigationLink {
                                    DetailView(item: item)
                                } label: {
                                    SearchCard(item: item)
                                        .frame(maxWidth: .infinity)
                                }
                            }
                        }
                    }
                }
                .scrollIndicators(.hidden) // 隐藏滚动条
                Spacer()
            }
            .background(Color("BgColor2"))
            .cornerRadius(15) // 添加圆角
            .padding(.horizontal,10)
            .padding(.bottom,10)
            
            
            
            
            Spacer()
        }
        .onAppear {
            // 确保视图出现时加载数据
            if !hasAppeared {
                // 执行首次加载的代码
                viewModel.get_tj_data()
                hasAppeared = true
            }
            
        }
        .padding(5)
        .background(Color("BgColor1"))
        .navigationBarBackButtonHidden()
        .ignoresSafeArea(edges: .bottom)
    }
}

struct SearchView_Previews: PreviewProvider {
    static var previews: some View {
        SearchView()
    }
}
